
package com.shai.wool.common.tags;

import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.shai.wool.common.SpringBeansTool;
import com.shai.wool.dictionary.entity.DictionaryVO;
import com.shai.wool.dictionary.service.DictionaryService;

/**
 * 根据字典数据配置生成枚举的radio，传入值默认选中对应项
 *
 * @author 朱国军
 * @since 1.0
 * @version 2016年3月28日 朱国军
 */
public final class DictionaryRadioTag extends TagSupport {
    
    private static Logger logger = Logger.getLogger(DictionaryRadioTag.class);
    
    private static final long serialVersionUID = -7177581356703711990L;

    private DictionaryService dictionaryService = SpringBeansTool.context.getBean(DictionaryService.class);

    private String fieldName;
    
    private String tableColumn;
    
    private String describe;
    
    private Integer value;

    private String type;

    /**
     * 获取枚举字段名称
     *
     * @return 枚举字段名称
     */
    public String getFieldName() {
        return fieldName;
    }

    /**
     * 设置枚举名称
     *
     * @param fieldName 枚举名称
     */
    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    /**
     * 获取枚举值key
     *
     * @return 枚举值key
     */
    public String getTableColumn() {
        return tableColumn;
    }

    /**
     * 设置枚举值key
     *
     * @param tableColumn 枚举值key
     */
    public void setTableColumn(String tableColumn) {
        this.tableColumn = tableColumn;
    }
    
    /**
     * 获取枚举字段描述
     *
     * @return 枚举字段描述
     */
    public String getDescribe() {
        return describe;
    }

    /**
     * 设置枚举描述
     *
     * @param name 枚举描述
     */
    public void setDescribe(String describe) {
        this.describe = describe;
    }

    /**
     * 获取枚举值
     *
     * @return 枚举值
     */
    public Integer getValue() {
        return value;
    }

    /**
     * 设置枚举值
     *
     * @param value 枚举值
     */
    public void setValue(Integer value) {
        this.value = value;
    }

    /**
     * 获取展示类型 edit：编辑页，query：列表查询,query_single:没有全选按钮
     *
     * @return 展示类型 edit：编辑页，query：列表查询,query_single:没有全选按钮
     */
    public String getType() {
        return type;
    }

    /**
     * 设置展示类型 edit：编辑页，query：列表查询,query_single:没有全选按钮
     *
     * @param type 展示类型 edit：编辑页，query：列表查询,query_single:没有全选按钮
     */
    public void setType(String type) {
        this.type = type;
    }

    @Override
    public int doEndTag() throws JspException {
        return DictionaryRadioTag.EVAL_PAGE;
    }
    
    @Override
    public int doStartTag() throws JspException {
        List<DictionaryVO> enumList = dictionaryService.queryList(tableColumn);
        if (StringUtils.equals("query", type) || StringUtils.equals("query_single", type)) {
            return writeQueryPage(enumList);
        } else {
            return writeEditPage(enumList);
        }
        
    }
    
    private int writeQueryPage(List<DictionaryVO> enumList) {
        StringBuilder builder = new StringBuilder();
        if (enumList != null && enumList.size() > 0) {
            int enumSize = enumList.size();
            String hiddenId = tableColumn + "_hid";

            builder.append("<dl class='clearfix invest-filter'>");
            builder.append("<dt>").append(describe).append("</dt>");
            builder.append("<dd class='clearfix'>");
            builder.append("<ul class='selection clearfix'>");

            if (StringUtils.equals("query", type)) {
                if (value == null || value == 0) {
                    builder.append("<li class='all cur' ");
                } else {
                    builder.append("<li ");
                }
                builder.append("onclick=\"javascript:setHiddenValue('").append(hiddenId).append("','')\">");
                builder.append("<a href='javascript:void(0);'><span>全部</span></a></li>");
            }

            for (int i = 0; i < enumSize; i++) {
                Integer itemValue = enumList.get(i).getDictionaryItem();
                
                if (value != null && enumList.get(i).getDictionaryItem() == value) {
                    builder.append("<li class='cur' ");
                } else {
                    builder.append("<li ");
                }
                builder.append("onclick=\"javascript:setHiddenValue('").append(hiddenId).append("','").append(itemValue).append("')\">");
                builder.append("<a href='javascript:void(0);'><span>").append(enumList.get(i).getItemName()).append("</span></a></li>");
                
            }
            builder.append("</ul></dd></dl>");
            builder.append("<input type='hidden' name='").append(fieldName).append("' id='").append(hiddenId).append("' ");
            builder.append("value='").append(value).append("' />");
        } else {
            logger.error("字典项转radio的Tag出错，根据tableColumn：" + tableColumn + "未找到对应数据字典");
            builder.append("error--根据tableColumn：" + tableColumn + "未找到对应数据字典");
        }
        JspWriter writer = this.pageContext.getOut();
        try {
            writer.write(builder.toString().trim());
        } catch (IOException e) {
            logger.error("字典项转radio的Tag出错", e);
        }
        return DictionaryRadioTag.SKIP_BODY;
    }
    
    private int writeEditPage(List<DictionaryVO> enumList) {
        StringBuilder builder = new StringBuilder();
        if (enumList != null && enumList.size() > 0) {
            int enumSize = enumList.size();
            builder.append("<div class='form-group'>");
            builder.append("<label class='col-sm-2 control-label'>").append(describe).append("</label>");
            builder.append("<div class='col-sm-10'>");
            builder.append("<ul class='selection clearfix'>");
            for (int i = 0; i < enumSize; i++) {
                String radioId = fieldName + "_" + i;
                builder.append("<li><div class='radio'>");
                builder.append("<input type='radio' name='").append(fieldName).append("' id='").append(radioId).append("' ");
                builder.append("value='").append(enumList.get(i).getDictionaryItem()).append("' ");
                if (value != null && enumList.get(i).getDictionaryItem() == value) {
                    builder.append("checked='true' ");
                }
                builder.append(">");
                builder.append("<label for='").append(radioId).append("'>").append(enumList.get(i).getItemName()).append("</label>");
                builder.append("</div></li>");
            }
            builder.append("</ul></div></div>");
        } else {
            logger.error("字典项转radio的Tag出错，根据tableColumn：" + tableColumn + "未找到对应数据字典");
            builder.append("error--根据tableColumn：" + tableColumn + "未找到对应数据字典");
        }
        JspWriter writer = this.pageContext.getOut();
        try {
            writer.write(builder.toString().trim());
        } catch (IOException e) {
            logger.error("字典项转radio的Tag出错", e);
        }
        return DictionaryRadioTag.SKIP_BODY;
    }
}
